<template>
  <el-dialog
    v-model="visible"
    class="logistics-dialog"
    width="580px"
    :destroy-on-close="true"
    :show-close="false"
    @close="handleClose"
  >
    <!-- 顶部标题栏 -->
    <template #header>
      <div class="dialog-header">
        <div class="header-title">
          <i class="el-icon-truck"></i>
          <span>物流轨迹</span>
        </div>
        <el-icon class="header-close" @click="close"><Close /></el-icon>
      </div>
    </template>

    <!-- 自主发货提示 -->
    <div v-if="isSelfShip" class="self-ship-box">
      <div class="self-ship-card">
        <h3>📦 当前快递为自主发货</h3>
        <p>请自行前往物流查询网站查看最新进度。</p>
        <div class="info-row">
          <span>运单号：</span>
          <el-tag type="info" size="small">{{ logisticsNo }}</el-tag>
        </div>
        <div class="btn-group">
          <el-button type="primary" size="large" @click="copyAndGo"> 复制单号并跳转查询 </el-button>
        </div>
        <p class="website-tip">
          查询网址：<a href="https://www.kuaidi100.com/" target="_blank"
            >https://www.kuaidi100.com/</a
          >
        </p>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-box">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 物流时间线 -->
    <div v-else-if="list.length > 0" class="timeline-wrap">
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in list"
          :key="index"
          :timestamp="item.time"
          placement="top"
          :color="getStatusColor(index)"
          size="large"
        >
          <div class="timeline-card" :class="{ active: index === 0 }">
            <div class="status-row">
              <span class="status-text">{{ item.routeCityName }} {{ item.operateSite }}</span>
              <span class="time-text">{{ item.operationTime }}</span>
            </div>
            <p class="desc">{{ item.operationRemark }}</p>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 空状态 -->
    <el-empty v-else description="暂无物流信息" class="empty-box" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { listLogisticsRecord } from '../../api/logistics';
import { cloneDeep, orderBy, reverse } from 'lodash';

const visible = ref(false);
const loading = ref(false);
const list = ref<any>([]);
const currentId = ref<string | null>(null);
const isSelfShip = ref(false);
const logisticsNo = ref<string>('');

// 弹窗展示
const show = async (row: any) => {
  const { logisticsId, logisticsNo: no, shippingType } = cloneDeep(row);
  logisticsNo.value = no || '';
  currentId.value = logisticsId;
  visible.value = true;

  if (shippingType === 2) {
    isSelfShip.value = true;
    return;
  }

  isSelfShip.value = false;
  await fetchLogistics(no);
};

// 关闭弹窗
const close = () => {
  visible.value = false;
};

// 复制并跳转
const copyAndGo = async () => {
  try {
    await navigator.clipboard.writeText(logisticsNo.value);
    ElMessage.success('运单号已复制，正在跳转查询网站...');
    window.open('https://www.kuaidi100.com/', '_blank');
  } catch (e) {
    ElMessage.error('复制失败，请手动复制');
  }
};

// 请求物流信息
async function fetchLogistics(id: string) {
  loading.value = true;
  list.value = [];
  try {
    const res: any = await listLogisticsRecord({ waybillNo: id });
    loading.value = false;
    if (res.code === 200) {
      const data = res.rows.map((v: any) => {
        if (!v.extendInfo) return v;
        return JSON.parse(v.extendInfo);
      });
      // lodash data 根据operationTime排序，最新的在最上面
      list.value = orderBy(data, ['operationTime'], ['desc']);
    } else {
      ElMessage.error(res.msg || '获取物流信息失败');
    }
  } catch (err) {
    loading.value = false;
    console.error('物流查询失败', err);
    ElMessage.error('获取物流信息失败');
  }
}

// 弹窗关闭事件
function handleClose() {
  visible.value = false;
  currentId.value = null;
  list.value = [];
  isSelfShip.value = false;
  logisticsNo.value = '';
}

const getStatusColor = (index: number): string => {
  return index === 0 ? '#67C23A' : '#909399';
};

defineExpose({
  show,
  close
});
</script>

<style scoped lang="scss">
.logistics-dialog {
  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 4px 10px;
    border-bottom: 1px solid #f0f0f0;

    .header-title {
      font-size: 18px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8px;
      color: #303133;
      i {
        color: #409eff;
        font-size: 20px;
      }
    }

    .header-close {
      cursor: pointer;
    }
  }

  .loading-box {
    padding: 24px;
  }

  .timeline-wrap {
    padding: 16px 24px 24px;
    max-height: 460px;
    overflow-y: auto;
  }

  .timeline-card {
    background: #fff;
    border-radius: 10px;
    padding: 12px 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    border: 1px solid #f2f2f2;
    transition: all 0.2s ease;
    &.active {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
    }
    .status-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .status-text {
        font-weight: 600;
        color: #303133;
        font-size: 15px;
      }
      .time-text {
        font-size: 13px;
        color: #999;
      }
    }
    .desc {
      font-size: 13px;
      color: #666;
      margin-top: 6px;
      line-height: 1.6;
    }
  }

  .self-ship-box {
    padding: 40px 20px;
    display: flex;
    justify-content: center;

    .self-ship-card {
      background: linear-gradient(135deg, #f0f7ff, #ffffff);
      border: 1px solid #d9ecff;
      border-radius: 12px;
      padding: 28px 30px;
      max-width: 420px;
      text-align: center;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
      h3 {
        font-size: 18px;
        font-weight: 600;
        color: #409eff;
        margin-bottom: 8px;
      }
      p {
        font-size: 14px;
        color: #606266;
        margin-bottom: 12px;
      }
      .info-row {
        margin: 12px 0;
        font-size: 14px;
        color: #333;
        display: flex;
        justify-content: center;
        gap: 8px;
      }
      .btn-group {
        margin-top: 10px;
      }
      .website-tip {
        font-size: 13px;
        color: #999;
        margin-top: 16px;
        a {
          color: #409eff;
          text-decoration: none;
          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }

  .empty-box {
    padding: 40px 0;
  }
}
</style>
